package mqConsumer

import (
	"context"
	"encoding/json"
	"github.com/Sir-yuChen/funAnalyse/global"
	"github.com/Sir-yuChen/funAnalyse/global/constant"
	"github.com/Sir-yuChen/funAnalyse/global/redisEnums"
	"github.com/Sir-yuChen/funAnalyse/model"
	"github.com/Sir-yuChen/funAnalyse/service/basisService"
	"github.com/Sir-yuChen/funAnalyse/utils/mongodb"
	"github.com/Sir-yuChen/funAnalyse/utils/socket"
	"go.mongodb.org/mongo-driver/bson"
	"go.uber.org/zap"
)

type CommunicationConsumerHandle struct{}

func (c *CommunicationConsumerHandle) Consumer(dataByte []byte) error {
	ctx := context.TODO()
	var informationOnUsers []model.InformationOnUser
	var senderUid = ""
	//1.json转map
	if err := json.Unmarshal(dataByte, &informationOnUsers); err != nil {
		global.GVA_LOG.Error("CommunicationConsumerHandle 数据转换异常", zap.Any("dataByte", string(dataByte)), zap.Error(err))
		return err
	}
	for _, informationOnUser := range informationOnUsers {
		//落库
		informationOnUser.InformationStatus = constant.MSG_STATUS_WILL_Processing
		if _, err := mongodb.CommInformationOnUserCollection.InsetOne(ctx, informationOnUser); err != nil {
			global.GVA_LOG.Error("新增消息记录基于用户异常", zap.Any("InformationOnUser", informationOnUser), zap.Error(err))
			return err
		}
		if informationOnUser.UserIdentity == constant.MSG_User_Identity_sender { //发送者
			informationOnUser.InformationStatus = constant.MSG_STATUS_WILL_Processe_success
			senderUid = informationOnUser.CustomerId
		} else if informationOnUser.UserIdentity == constant.MSG_User_Identity_recipient {
			/*
				判断用户是否登录，登录入库并写入长连接，不在线，入库，消息状态为待读取
			*/
			result, err := global.GVA_REDIS.Exists(context.Background(), informationOnUser.CustomerId+redisEnums.USER_ROLE_KEY_SUFFIX).Result()
			if err != nil {
				global.GVA_LOG.Error("redis异常", zap.Any("InformationOnUser", informationOnUser), zap.Error(err))
				return err
			}
			if result != 0 { //存在client = {[]*socket.Client} len:2, cap:2
				//好友请求写入长连接
				client := socket.GetClient(informationOnUser.CustomerId)
				for _, cl := range client {
					if cl.UseMark == global.ChatStock {
						var message socket.ServiceMessage
						//查用户名
						info, err := basisService.NewUserService().GetUserInfo(senderUid)
						if err != nil {
							global.GVA_LOG.Error("查用户名异常", zap.Any("UserId", senderUid), zap.Error(err))
							return err
						}
						content := socket.ServiceMessageContent{
							Body: "收到来自账户" + info.CustomerName + "的好友请求",
						}
						message.Type = constant.MSG_TYPE_friend
						message.Content = content
						cl.Send(message)
					}
				}
				if len(client) >= 1 {
					informationOnUser.InformationStatus = constant.MSG_STATUS_WILL_Processe_success
				} else {
					informationOnUser.InformationStatus = constant.MSG_STATUS_WILL_processed
				}
			} else { //不存在
				informationOnUser.InformationStatus = constant.MSG_STATUS_WILL_processed
			}
		}
		update := bson.D{{"$set",
			bson.D{
				{"informationstatus", informationOnUser.InformationStatus},
			},
		}}
		filter := bson.M{"customerid": informationOnUser.CustomerId, "informationid": informationOnUser.InformationId}
		if _, err := mongodb.CommInformationOnUserCollection.UpdateOne(ctx, filter, update); err != nil {
			global.GVA_LOG.Error("修改消息状态异常", zap.Any("InformationOnUser", informationOnUser), zap.Error(err))
			return err
		}
	}
	return nil
}

func (c *CommunicationConsumerHandle) FailAction(dataByte []byte) error {
	global.GVA_LOG.Error("CommunicationConsumerHandle  消息执行异常  FailAction", zap.Any("dataByte", string(dataByte)))
	return nil
}
